package com.bus.boot.action;

import java.io.IOException;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.bus.common.image.ImageScale;
import com.bus.common.image.ImageUtils;
import com.bus.common.upload.FileRepository;
import com.bus.common.web.ResponseUtils;
import com.bus.common.web.springmvc.RealPathResolver;
import com.bus.core.entity.BusSite;
import com.bus.core.entity.BusUser;
import com.bus.core.manager.BusUserMng;
import com.bus.core.web.WebCoreErrors;
import com.bus.core.web.WebErrors;
import com.bus.core.web.util.BusUtils;

/**
 * @author Tom
 */
public class CommonUpload {

	protected void swfPicsUpload(
			String root,
			Integer uploadNum,
			@RequestParam(value = "Filedata", required = false) MultipartFile file,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) throws Exception {
		JSONObject data = new JSONObject();
		WebCoreErrors errors = validateImage(file, request);
		if (errors.hasErrors()) {
			data.put("error", errors.getErrors().get(0));
			ResponseUtils.renderJson(response, data.toString());
		} else {
			BusSite site = BusUtils.getSite(request);
			String ctx = request.getContextPath();
			String origName = file.getOriginalFilename();
			String ext = FilenameUtils.getExtension(origName).toLowerCase(
					Locale.ENGLISH);
			String fileUrl;
			fileUrl = fileRepository
					.storeByExt(site.getUploadPath(), ext, file);
			// 加上部署路径
			if (StringUtils.isNotBlank(ctx)) {
				fileUrl = ctx + fileUrl;
			}
			busUserMng.updateUploadSize(BusUtils.getUserId(request),
					Integer.parseInt(String.valueOf(file.getSize() / 1024)));
			data.put("imgUrl", fileUrl);
			ResponseUtils.renderText(response, data.toString());
		}
	}

	protected void swfAttachsUpload(
			String root,
			Integer uploadNum,
			@RequestParam(value = "Filedata", required = false) MultipartFile file,
			HttpServletRequest request, HttpServletResponse response,
			ModelMap model) throws Exception {
		JSONObject data = new JSONObject();
		WebCoreErrors errors = validateUpload(file, request);
		if (errors.hasErrors()) {
			data.put("error", errors.getErrors().get(0));
			ResponseUtils.renderJson(response, data.toString());
		} else {
			BusSite site = BusUtils.getSite(request);
			String ctx = request.getContextPath();
			String origName = file.getOriginalFilename();
			String ext = FilenameUtils.getExtension(origName).toLowerCase(
					Locale.ENGLISH);
			// TODO 检查允许上传的后缀
			String fileUrl = "";
			try {
				fileUrl = fileRepository.storeByExt(site.getUploadPath(), ext,
						file);
				// 加上部署路径
				fileUrl = ctx + fileUrl;
				busUserMng
						.updateUploadSize(
								BusUtils.getUserId(request),
								Integer.parseInt(String.valueOf(file.getSize() / 1024)));
				model.addAttribute("attachmentPath", fileUrl);
			} catch (IllegalStateException e) {
				model.addAttribute("error", e.getMessage());
			} catch (IOException e) {
				model.addAttribute("error", e.getMessage());
			}
			data.put("attachUrl", fileUrl);
			data.put("attachName", origName);
			ResponseUtils.renderJson(response, data.toString());
		}
	}

	/**
	 * 验证图片（图片有格式需求系统设定）
	 * 
	 * @param file
	 * @param request
	 * @return
	 */
	protected WebCoreErrors validateImage(MultipartFile file,
			HttpServletRequest request) {
		BusUser user = BusUtils.getUser(request);
		WebCoreErrors errors = WebCoreErrors.create(request);
		if (file == null) {
			errors.addErrorCode("imageupload.error.noFileToUpload");
			return errors;
		}
		String filename = file.getOriginalFilename();
		if (StringUtils.isBlank(filename)) {
			filename = file.getOriginalFilename();
		}
		if (filename != null && filename.indexOf("\0") != -1) {
			errors.addErrorCode("upload.error.filename", filename);
		}
		String ext = FilenameUtils.getExtension(filename);
		if (!ImageUtils.isValidImageExt(ext)) {
			errors.addErrorCode("imageupload.error.notSupportExt", ext);
			return errors;
		}
		try {
			if (!ImageUtils.isImage(file.getInputStream())) {
				errors.addErrorCode("imageupload.error.notImage", ext);
				return errors;
			}
		} catch (IOException e) {
			errors.addErrorCode("imageupload.error.ioError", ext);
			return errors;
		}
		// 验证文件大小
		errors = validateFile(file, user, request);
		return errors;
	}

	/**
	 * 验证附件
	 * 
	 * @param file
	 * @param request
	 * @return
	 */
	protected WebErrors validateUpload(MultipartFile file,
			HttpServletRequest request) {
		String origName = file.getOriginalFilename();
		BusUser user = BusUtils.getUser(request);
		String ext = FilenameUtils.getExtension(origName).toLowerCase(
				Locale.ENGLISH);
		WebErrors errors = WebErrors.create(request);
		if (errors.ifNull(file, "file", true)) {
			return errors;
		}
		if (origName != null && origName.indexOf("\0") != -1) {
			errors.addErrorCode("upload.error.filename", origName);
		}
		errors = validateFile(file, user, request);
		return errors;
	}

	protected WebErrors validateFile(MultipartFile file, BusUser user,
			HttpServletRequest request) {
		String origName = file.getOriginalFilename();
		int fileSize = (int) (file.getSize() / 1024);
		WebErrors errors = WebErrors.create(request);
		if (origName != null && origName.indexOf("\0") != -1) {
			errors.addErrorCode("upload.error.filename", origName);
		}
		return errors;
	}

//	@Autowired
	protected FileRepository fileRepository;
//	@Autowired
	protected ImageScale imageScale;
//	@Autowired
	protected RealPathResolver realPathResolver;
//	@Autowired
	protected BusUserMng busUserMng;
}
